package Introspector;

import lombok.extern.slf4j.Slf4j;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryPoolMXBean;

import static logsdk.travel.EnvironmentInformation.*;

/**
 * Created by zhaoxiang on 2019/4/23.
 */
@Slf4j
public class MemoryDemo {
    static String mb(long s) {
        return String.format("%d (%.2f M)", s, (double) s / (1024 * 1024));
    }

    public static void main(String[] args) {
        System.out.println("Runtime max: " + mb(Runtime.getRuntime().maxMemory()));
        MemoryMXBean m = ManagementFactory.getMemoryMXBean();

        System.out.println("Non-heap: " + mb(m.getNonHeapMemoryUsage().getMax()));
        System.out.println("Heap: " + mb(m.getHeapMemoryUsage().getMax()));

        for (MemoryPoolMXBean mp : ManagementFactory.getMemoryPoolMXBeans()) {
            System.out.println("Pool: " + mp.getName() + " (type " + mp.getType() + ")" + " = " + mb(mp.getUsage().getMax()));
        }

        logEnvironmentInfo();
    }



    public static void logEnvironmentInfo() {

            String jvmVersion = getJvmVersion();
            String[] options = getJvmStartupOptionsArray();

            String javaHome = System.getenv("JAVA_HOME");

            long maxHeapMegabytes = getMaxJvmHeapMemory() >>> 20;

            log.info("--------------------------------------------------------------------------------");
             log.info(" OS current user: " + System.getProperty("user.name"));
             log.info(" JVM: " + jvmVersion);
            log.info(" Maximum heap size: " + maxHeapMegabytes + " MiBytes");
            log.info(" JAVA_HOME: " + (javaHome == null ? "(not set)" : javaHome));

            if (options.length == 0) {
                log.info(" JVM Options: (none)");
            }
            else {
                log.info(" JVM Options:");
                for (String s: options) {
                    log.info("    " + s);
                }
            }

            log.info(" Classpath: " + System.getProperty("java.class.path"));

            log.info("--------------------------------------------------------------------------------");
        }

}